/* 工程名称界面js */
(function() {
	/*'use strict';*/
	require(['jquery', 'box', 'bootstrapTable', 'bootstrapTableZh', 'form'],function(jquery, box) {
		
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		
		if(typeof $.fn.form === 'undefined') {
			throw new Error('form依赖项未能加载');
		}
		
		var $table = $('#itemCategory_retrieve'),	//jquery包装table对象，使其能够调用扩展后jquery的方法
			$addBtn = $('#itemCategory_add'),
			formId = 'itemCategory_create_form',
			formId2 = 'itemCategory_update_form',
	    	selections = [];
		
		function initTable() {//加载内容
			$table.bootstrapTable({
				width: '90%',
				columns: [
	      			{width: '40%', field: 'name', title: '工程名称', align: 'center'},
	      			{width: '40%', field: 'description', title: '描述', align: 'center'},
	      			{width: '15%', field: 'crud', title: '操作', align: 'center', events: orgEvents, formatter: operateFormatter}]
	        });
	        
			setTimeout(function () {
	            $table.bootstrapTable('resetView');
	        }, 200);
	        
	        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
	        	var detail = detailFormatter(index, row);
	        	$detail.html(detail);
	        });
	        $table.on('all.bs.table', function (e, name, args) {
	            console.log(name, args);
	        });
	    }
		
		function getIdSelections() {
	        return $.map($table.bootstrapTable('getSelections'), function (row) {
	            return row.id;
	        });
	    }
	    function responseHandler(res) {
	        $.each(res.rows, function (i, row) {
	            row.state = $.inArray(row.id, selections) !== -1;
	        });
	        return res;
	    }
	    
	    /*table中  “+” 按钮添加内容*/
	    function detailFormatter(index, row) {
	        var html = [], Updater = "", updateTime = "";
	        if(row.updatetime == null || row.updater == null){
	        	Updater = "无";
	        	updateTime = "无";
	        }else {
		    	Updater = row.updater;
		    	updateTime = new Date(row.updatetime).toLocaleString();
	        }
            html.push('<p><b>创建者 :</b> ' + row.creater + '</p>'+
            		'<p><b>创建时间 :</b> ' + new Date(row.createtime).toLocaleString() + '</p>'+
            		'<p><b>更新者 :</b> ' + Updater + '</p>'+
            		'<p><b>更新时间:</b> ' + updateTime + '</p>');
	        return html.join('');
	    }
	    
	    function operateFormatter(value, row, index) {
	    	
	        return [
				'<a class="edit" href="javascript:void(0)" title="edit">',
				'<i class="glyphicon glyphicon-edit"></i>',
				'</a>  ',
				'<a class="remove" href="javascript:void(0)" title="remove">',
				'<i class="glyphicon glyphicon-remove"></i>',
	            '</a>  '	            
	        ].join('');
	    }
	    
	    window.orgEvents = {
	        'click .remove': function (e, value, row, index) {
	        	var name = row.name;
	        	var modalObj = box.configModal('subPage'),
	        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
	        	var modal = $('#' + modalId), 
    			btn_sure = $('#' + btnSure);
	        	$('#' + modalBodyId).html('确定要删除"' + name + '"吗？');
	        	modal.modal({backdrop: "static"});
	        	
	        	btn_sure.unbind("click").bind("click", function() {
	        		btn_sure.attr('disable', true);
	        		$.ajax({
		        		url: "projectCotegory/deleteProjectCotegory.service",
		        		type: "post",
		        		data: {id: row.id},
		        		success: function(data) {
		        			if(data && data.success) {
		        				ajaxRequest();
		        				modal.modal("hide");
		        			} else{
		        				var modalObj = box.tipModal('subPage'),
	    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId);
				        		modal.modal("hide");
				        		$('#' + modalBodyId).html('工程删除失败。。。。');
				        		tip_modal.modal();
				        	}
		        		},
		        		error: function() {},
		        		complete : function() {
		        			btn_sure.attr('disable', false);
		        		}
		        	});
	        	});
	        },
	        'click .edit': function (e, value, row, index) {
	        	var editdata = row;
	        	var modalObj = box.loadUpdateModal('subPage', "修改工程名称"),
	    			modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
	        	var updateUrl = "system/getPage.service?path=businessManage/projectLibrary/itemCategoryUpdate",
	        		_target = modalBodyId, _selector= "#itemCategory_update";
	        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response){
	        		var modal = $('#' + modalId), 
	        			btn_sure = $('#' + btnSure);
	    			$('#'+formId2).form('load', editdata);
	    			$('#subPage').data('row', row);
	    			modal.modal({backdrop: "static"});
	    			btn_sure.unbind('click').bind('click', function() {
	    				$('#itemCategory_update_form').data('bootstrapValidator').validate();
	    				var submitData = {}, flag = $('#itemCategory_update_form').data('bootstrapValidator').isValid();
						if(flag) {
							btn_sure.attr('disable', true);
		    				submitData = $('#'+formId2).form('getFormData', {id:formId2});
		    				submitData['oid'] = $('#update_name').val();
		    				$.ajax({
		    					url: 'projectCotegory/updateProjectCotegory.service',
		    					type: 'post',
		    					data: submitData,
		    					success: function(data) {
		    						var modalObj = box.tipModal('subPage'),
		    			        		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
		    			        	var tip_modal = $('#' + modalId);
		    						if(data && data.success) {
				        				ajaxRequest();
			    	    	            modal.modal('hide');
							        	$('#' + modalBodyId).html('工程名称修改成功！！');
						        		tip_modal.modal();
		    						} else {
		    							modal.modal('hide');
		    				        	if(data.errorCode == "2001" || data.errorCode == "1002"){
		    				        		$('#' + modalBodyId).html('工程名称修改失败。。。。');
		    				        	}else{
		    				        		$('#' + modalBodyId).html('工程名称修改失败，网络异常。。。。');
		    				        	}
	    				        		tip_modal.modal();
		    						}
		    					},
		    					complete: function() {
		    						btn_sure.attr("disabled", false);
		    					},
		    					error: function() {}
		    				});
						}
	    			});
	        	}});
	        }
	    };
	    
	    function ajaxRequest() {
	    	$.ajax({
				url:"projectCotegory/retieveProjectCotegorys.service",
				type: 'post',
				success: function(data) {
					$table.bootstrapTable('load', data.data);
				},
				complete: function() {
				}
			});
	    }
	    
	    $addBtn.click(function () {
	    	//弹出模态框
	    	var modalObj = box.loadCreateModal('subPage', "创建工程"),
	    		modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
	    	
	    	var createUrl = "system/getPage.service?path=businessManage/projectLibrary/itemCategoryCreate",
        		_target = modalBodyId, _selector= "#itemCategory_create";
	    	
        	orange.loadPage({url: createUrl, target: _target, selector: _selector, success: function(response){
        		var modal = $('#' + modalId);
    			modal.modal({backdrop: "static"});
    			var btn_sure = $('#' + btnSure);
    			
    			btn_sure.unbind('click').bind('click', function(btn) {
    				/*整体页面校验*/
					$('#itemCategory_create_form').data('bootstrapValidator').validate();
					var jsonData = {}, flag = $('#itemCategory_create_form').data('bootstrapValidator').isValid();
					if(flag) {
						btn_sure.attr("disabled", true);
	    				jsonData = $('#'+formId).form('getFormData', {id:formId});
	    				$.ajax({
	    					url: 'projectCotegory/createProjectCotegory.service',
	    					type: 'post',
	    					data: jsonData,
	    					success : function(data) {
	    						var modalObj = box.tipModal(''),
	    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId);
	    						if(data && data.success) {
	    							$table.bootstrapTable('prepend', data.data);
	        	    	            modal.modal('hide');
	    						}else {
	    							modal.modal('hide');
	    							if(data.errorCode == "1002" || data.errorCode == "3001"){
	    				        		$('#' + modalBodyId).html('工程创建失败。。。。');
	    				        	}else if(data.erroeCode == "2003"){
	    				        		$('#' + modalBodyId).html('工程创建失败，该条数据已存在。。。。');
	    				        	}else{
	    				        		$('#' + modalBodyId).html('工程创建失败，网络异常。。。。');
	    				        	}
	    				        	tip_modal.modal();
	    						}
	    					},
	    					error: function() {
	    						modal.modal('hide');
	    						var modalObj = box.tipModal('subPage'),
	    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId);
					        	$('#' + modalBodyId).html('工程创建失败，网络异常。。。。');
				        		tip_modal.modal();
	    					},
	    					complete: function() {
	    						btn_sure.attr("disabled", false);
	    					}
	    				});
					}
    			});
        	}});
	    });
	    
	    initTable();
	    ajaxRequest();
	});
})();
